// src/store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: '',
    isLoggedIn: false,
    menus: {
      public: [
        { key: 'index', title: '首页', route: '/index' },
        { key: 'items', title: '项目管理', route: '/items' },
        { key: 'students', title: '学生管理', route: '/students' },
        { key: 'record', title: '体侧记录', route: '/record' },
        { key: 'calendar', title: '体检日历', route: '/calendar' },
      ],
    }
  },
  mutations: {
    setUser(state, user) {
      console.log('user:' + JSON.stringify(user))
      state.user = user;
      state.isLoggedIn = !!user;
    },
    logout(state) {
      state.user = '';
      state.isLoggedIn = false;
    }
  },
  actions: {
    login({ commit }, user) {
      console.log('user:' + JSON.stringify(user))
      commit('setUser', user);
    },
    setUserRole({ commit }, role) {
      const user = { role: role };
      commit('setUser', user);
    },
    login2({ commit }, { token, role }) {
      const user = { token, role };
      commit('setUser', user);
    },
    logout({ commit }) {
      commit('logout');
    }
  },
  getters: {
    currentUser: state => {
      return state.user || 'Guest'; // 如果没有用户信息，则显示 "Guest"
    },
    userMenus: state => {
      const publicMenus = state.menus.public || [];
      const roleMenus = state.menus[state.user.role] || [];
      return publicMenus.concat(roleMenus);
    },
    isLoggedIn(state) {
      return state.isLoggedIn;
    }
  },
  plugins: [
    // 默认使用 localStorage 存储所有 state
    createPersistedState(),
  ],
});
